/**
 * Created by wang.cheng on 2016/1/13.
 */
/**
 * Created by shenhai on 15/10/15.
 */

angular.module('mis.creatorManager.controllers', [])
    .controller('creatorApplyCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {


        $scope.currentPage = 1;
        $scope.pageSize = 15;

        //分页
        $scope.pagination = new pagination({
            currentPage: $scope.currentPage, pageSize: $scope.pageSize,
            url: 'http://' + backOfficeHost + '/rest/v1.0/mis/appUser/roleApplyList/:page/:size',
            ajax: $http,
            success: function (data) {
                $scope.applyList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共" + $scope.pageNumber + "页 有" + $scope.count + "数据");

            },
            error: function (err) {
                $scope.applyList = null;
            },
            params: {type: 4}
        });

        //搜索
        $scope.search = function (temp) {
             var btn = temp.target;

            $scope.pagination.currentPage = 1;
            $scope.currentPage = 1;

            //var community = $scope.cascading.getVillageId(btn);

            var body = {type: 4};
            //if (community) body.community = community;
            if ($scope.status) body.status = $scope.status;
            if ($scope.city) body.city = $scope.city;
            if ($scope.userId) body.user = $scope.userId;
            if ($scope.nickName) body.name = $scope.nickName;
            if ($scope.mobilePhone) body.phone = $scope.mobilePhone;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/roleApplyList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if(data && data.result && data.result.status == '0') {
                    alert('请输入合法的申请人ID!');
                    return;
                }
                if(data && data.data) {
                    $scope.applyList = data.data.list;
                    $scope.pageNumber = data.data.totalPage;
                    $scope.count = data.data.count;

                    $scope.pagination.totalPage = data.data.totalPage;
                }
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;
            }).error(function (err) {
                $scope.applyList = null;
                alert(err);
            });

        };

        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };


        $scope.declineShow = function (apply) {
            $scope.apply = apply;

            var body = {
                community: apply.community.objId,
                userRole: 4
            };
            <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start -->
            // $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/appUserList/1/10', body, {
            //     headers: {'Content-Type': 'application/json;charset=utf-8'}
            // }).success(function (data) {
            //
            //     if (Number(data.result.status) == 1) {
            //         if (data.data.count > 0) {
            //             /*  宝宝树66小区二次改造    mod   guo.xiaomin  20171015  start   */
            //             /*  宝宝树66小区二次改造    mod   zhangm  20170721  start   */
            //             /*$scope.apply.msg = "该小区的" + data.data.list[0].nickName + "已经成为创始人了哦，你玩来了一步";*/
            //             if(data && data.data && data.data.list) {
            //                 $scope.apply.msg = "该小区的" + data.data.list[0].nickName + "已经成为小区大使了哦，你玩来了一步";
            //             } else {
            //                 // 没有小区大使时候的拒绝
            //                 $scope.apply.msg = "小6很遗憾的告诉你，你申请的" + apply.community.communityName + "小区大使，由于没有达到目标，申请失败了";
            //             }
            //             /*  宝宝树66小区二次改造    mod   zhangm  20170719   end   */
            //             /*  宝宝树66小区二次改造    mod   guo.xiaomin  20171015   end   */
            //         } else {
            //             /*  宝宝树66小区二次改造    mod   zhangm  20170721  start   */
            //             /*$scope.apply.msg = "小6很遗憾的告诉你，你申请的" + apply.community.communityName + "小区的创始人，由于没有达到目标，申请失败了";*/
            //             $scope.apply.msg = "小6很遗憾的告诉你，你申请的" + apply.community.communityName + "小区大使，由于没有达到目标，申请失败了";
            //             /*  宝宝树66小区二次改造    mod   zhangm  20170721  end   */
            //         }
            //         $('#doc-modal-reject').modal({target: '#doc-modal-reject', width: 600, height: 350});
            //     } else {
            //
            //         alert('系统错误，请联系管理员！');
            //     }
            // });

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/getDeclineReasonMessageList', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data && data.data[0]) {
                    $scope.declineMsg = data.data[0];
                }
                var selectedDiv="<select id='selectedDivId'>";
                for(var i=0;i<data.data[0].length;i++) {
                    if ( i== 0) {
                        selectedDiv+="<option value='"+data.data[0][i].message+"' selected='selected'>"+data.data[0][i].message+"</option>";
                    } else {
                        selectedDiv+="<option value='"+data.data[0][i].message+"' >"+data.data[0][i].message+"</option>";
                    }
                }
                selectedDiv+="</select>";
                if ($("#selectedDivId").length > 0) {
                    $("#selectedDivId").remove();
                }
                $("#optsValues").append(selectedDiv);
            });
            ///////////////////////////////////////////////////

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/appUserList/1/10', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (Number(data.result.status) == 1) {
                    if (data.data.count > 0) {
                        $("#textMsgArea").val($("#selectedDivId option:selected").text());
                        $scope.apply.msg = "亲，您本次申请小区大使不成功，请您提供正确的微信号哦";
                    } else {
                        $("#textMsgArea").val($("#selectedDivId option:selected").text());
                        $scope.apply.msg = "亲，您本次申请的" + apply.community.communityName + "小区的创始人不成功，请您提供正确的微信号哦";
                    }
                    $("#selectedDivId").on('change',function() {
                        var messageValues=$("#selectedDivId option:selected").text();
                        $("#textMsgArea").val($("#selectedDivId option:selected").text());
                    });
                    $('#doc-modal-reject').modal({target: '#doc-modal-reject', width: 600, height: 350});
                } else {
                    alert('系统错误，请联系管理员！');
                }
            });
            <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end -->
        };

        <!--  宝宝树66小区二次改造    add   gct  20170810   start   -->
        $scope.cencelShow = function (apply) {
            $scope.apply = apply;

            var body = {
                community: apply.community.objId,
                userRole: 4
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/getCancelReasonMessageList', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                //$("#optionsValues").html();
                /*
                 data.data.options*/
               /* alert(data.data[0]);
                alert(data.data.message);
                alert(data.data[0].length);
                alert(data.data[0][0].message);*/
                var selectedDiv="<select id='selectedDivId'>";

                for(var i=0;i<data.data[0].length;i++)
                {
                    if(i==0)
                    {
                        selectedDiv+="<option value='"+data.data[0][i].message+"' selected='selected'>"+data.data[0][i].message+"</option>";
                    }
                    else
                    {
                        selectedDiv+="<option value='"+data.data[0][i].message+"' >"+data.data[0][i].message+"</option>";
                    }

                }
                selectedDiv+="</select>";
                if ($("#selectedDivId").length > 0) {
                    $("#selectedDivId").remove();
                }
                $("#optionsValues").append(selectedDiv);
            });
            ///////////////////////////////////////////////////



            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/appUserList/1/10', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

               /* $("#optionsValues").html();
                data.data.options*/

                if (Number(data.result.status) == 1) {
                    if (data.data.count > 0) {
                        $("#textAreaMsg").val($("#selectedDivId option:selected").text());
                        $scope.apply.msg = "小6很遗憾的告诉你，现在撤销你的大使";
                    } else {
                        $("#textAreaMsg").val($("#selectedDivId option:selected").text());
                        $scope.apply.msg = "小6很遗憾的告诉你，你申请的" + apply.community.communityName + "小区的创始人，现在撤销你的大使";
                    }
                    $("#selectedDivId").on('change',function()
                    {
                       // alert($("#selectedDivId option:selected").text());
                        var messageValues=$("#selectedDivId option:selected").text();

                          //  $scope.apply.msg="";
                            $("#textAreaMsg").val($("#selectedDivId option:selected").text());
                           // $("#textAreaMsg").text($("#selectedDivId option:selected").text());


                    });
                    $('#doc-modal-pullblackOK').modal({target: '#doc-modal-pullblackOK', width: 600, height: 350});
                } else {

                    alert('系统错误，请联系管理员！');
                }
            });

        };


        <!--  宝宝树66小区二次改造    add   gct  20170810   end   -->

        $scope.handleApply = function (status, apply) {

            var body = {
                id: apply.objId,
                applyCity: apply.cityId,
                applyCommunity: apply.community.objId,
                applyCommunityName: apply.community.communityName,
                user: apply.user,
                status: status,
                type: 4
            };

            /*  宝宝树66小区二次改造    mod   gct  20170823  start   */
            /* if (!status) body.msg = apply.msg;  旧*/
            if (status == 3)
            {
            body.msg = $("#textAreaMsg").val();
                status=false;
            body.status=false;
                <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start -->
                body.operateType = 'cancel'; // 取消创始人
                <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end -->
        }

            else if(status==2) {
                <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start -->
                // body.msg = apply.msg;
                body.msg = $("#textMsgArea").val();
                body.operateType = 'decline';// 拒绝创始人申请
                body.roleApplyStatus = -2;
                if ($("#textMsgArea").val() == $scope.declineMsg[0].message) {
                    body.roleApplyStatus = -2;
                }
                if ($("#textMsgArea").val() == $scope.declineMsg[1].message) {
                    body.roleApplyStatus = -3;
                }
                <!-- 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end -->
                status=false;
                body.status=false;
            }

            /*  宝宝树66小区二次改造    mod   gct  20170823  start   */
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/roleApplyStatus', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

               /* alert(data.data.status);*/
                if (data.result.status == 1) {
                    if (status) {
                        /*  宝宝树66小区二次改造    add   gct  20170811  start   */
                        if(data.data.status == 999)
                        {
                            alert("本小区已有小区大使！");
                        }
                        else if(data.data.status == 888)
                        {
                            alert("本用户已经不在本小区了！");
                        } else {
                            apply.status = status ? 1 : -1;
                        }
                        /*  宝宝树66小区二次改造    add   gct  20170811  end   */
                        $('#doc-modal-pullblackOK').modal("close");
                        $('#doc-modal-reject').modal("close");
                    } else {
                        apply.status = status ? 1 : -1;
                        /*  宝宝树66小区二次改造    mond   guo.xiaomin  20170816  start   */
                        $('#doc-modal-pullblackOK').modal("close"); // 撤销
                        $('#doc-modal-reject').modal("close"); // 拒绝
                        /*  宝宝树66小区二次改造    mond   guo.xiaomin  20170816  end   */
                    }
                }
                else {
                    alert("请求失败！");
                }

            }).error(function (err) {
                alert("请求失败！");
            });

        };

        /*  宝宝树66小区二次改造    mod   chenf  20170802  start   */
        /*权限设置*/
        $scope.powerSet = function (status, apply) {
            if(status == false){
                var body = {
                    userId: apply.userId
                };
            }else {
                var body = {
                    userId: apply.user.objId
                };
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/roleApplyPowerSet', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.result.status == 1) {

                    if(status == false){
                        $scope.userId = apply.userId;
                        $scope.communityName = apply.communityName
                    }else {
                        $scope.userId = apply.user.objId;
                        $scope.communityName = apply.community.communityName
                    }
                    $scope.communityList = data.data.communityList;
                    if(data.data.communityList != null && data.data.communityList.length >0 ){
                        $scope.statu = 1;
                    }
                    $('#doc-modal-Detail').modal({target: '#doc-modal-Detail', width: 1000, height: 520});
                }else {
                    alert("请求失败！");
                }
            }).error(function (err) {
                alert("请求失败！");
            });

        };

        // 保存用户的小区分配信息
        $scope.saveCommunitySet = function() {
            var userId = $("#userId").val();
            var body = {userID: userId, user:{}};
            var community = $("#cascad-edit").find(".c-village")[0].dataset.cId;
            var communityVal = $("#cascad-edit").find(".c-village")[0].value;
            var cityId = $("#cascad-edit").find(".c-citys")[0].dataset.cId;
            if(cityId) body.user.cityId = cityId;

            if(community) {
                body.user.community = community;
            }else{
                /*  宝宝树66小区二次改造    mod   gct  20170823   start   */

                body.communityValue=communityVal;
                /*  alert('请选择小区'); 旧
                 return;*/
                /*  宝宝树66小区二次改造    mod   gct  20170823   end   */

            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/saveCommunitySet', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $('#doc-modal-Detail').modal("close");
                $scope.search(true);
                if (Number(data.result.status) == 1) {
                    if(data!=null&&typeof(data.data.status)!='undefined'&&Number(data.data.status)==999)
                    {
                        alert("请仔细确认小区名");
                    }
                    else
                    {
                        alert('保存成功');
                    }


                }else {

                    alert('保存失败');
                }
            }).error(function () {
                $('doc-modal-Detail').modal("close");
                $scope.search(true);
                alert('保存失败');
            });
        };

        /*编辑小区权限*/
        $scope.powerEdit = function (communityList) {
            var communityList = communityList;
            $('#doc-modal-Detail_2').modal({target: '#doc-modal-Detail', width: 500, height: 400});

        };
        // 编辑用户的小区分配信息
        $scope.editCommunitySet = function(communityList) {
            var community = [];
            // 获取选中的小区
           $('input[name="community"]:checked').each(function(){
               community.push($(this).val());
            });
            var body = {
                community : community,
                userId:communityList[0].user
            };

            var user = {
                userId:communityList[0].user,
                communityName:$scope.communityName
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/editCommunitySet', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $('#doc-modal-Detail_2').modal("close");

                if (Number(data.result.status) == 1) {
                    alert('修改成功');
                    $scope.powerSet(false,user);
                }else {
                    alert('修改失败');
                }
            }).error(function () {
                $('doc-modal-Detail_2').modal("close");
                $scope.powerSet(false,user);
                alert('修改失败');
            });
        };

        //级联框
        var cascadData = {
            provinceUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionPrivince',
            cityUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCity',
            cityAreaUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCounty',
            villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/mis/appUser/villageService',
            ajax: $http
        };
        $scope.cascading = new gObj.cascading(cascadData);
        $scope.cascading.paint($(".city-cascading")[0],true);
        /*  宝宝树66小区二次改造    mod   chenf  20170802  end   */
    }]);
